import React from 'react'
import MyNavBar from '@/components/MyNavBar'
import {
  List,
  Avatar,
  Space,
  Ellipsis,
  Stepper,
  Checkbox,
  Empty,
  Button,
  SwipeAction,
  Dialog
} from 'antd-mobile'
// import { Action,SwipeActionRef } from 'antd-mobile/es/components/swipe-action'
import { 
  getCartListApi,
  updateNumApi,
  selectOneApi,
  selectAllApi,
  removeApi
} from '@/api/cart'
import { useEffect, useState, useMemo } from 'react'
import { useSelector } from 'react-redux'
import { useHistory } from 'react-router-dom'
import styled from 'styled-components'
import { useCallback } from 'react'

const BarStyle = styled.div`
  display:flex;
  justify-content:space-around;
  height:50px;
  width:100%;
  align-items:center;
  position:fixed;
  left:0;
  bottom:0;
  background-color:#fff;
`
export default function Cart() {
  const his = useHistory()
  // 定义购物车列表数据
  const [cartList, setCartList] = useState([])
  // 获取仓库数据
  const { userId } = useSelector(state => state)

  // 不希望函数被反复创建,可以用useCallback; [ 这样 调用可以多次,创建只有一次, 节省性能]
  const getCartListFn = useCallback(()=>{
    getCartListApi({
      userid: userId
    }).then(res => {
      console.log('cartres', res);
      if (res.data.code == '200') {
        setCartList(res.data.data)
        // 判断全选状态是否全选 -- 根据res.data.data.flag 
        let flag = res.data.data.every(item => item.flag)
        setCheckedAll(flag)
      } else {
        setCartList([])
        setCheckedAll(false)
      }
    })
  },[])
  // 购物车数据请求
  useEffect(() => {
    getCartListFn()
  }, [])
  // 使用useMemo计算属性
  const isShowEmpty = useMemo(() => cartList.length > 0 ? false : true, [cartList])

  // 计算总价: 计算属性
  // const 总价 = useMemo(()=>return { 返回值},[依赖的数据:购物车数组cartList])
  // const sum = arr.reduce((sum,item)=>{return  sum+=item },sum的初始值)
 const totalPrice = useMemo(()=>{
  // return的返回值 就是计算属性的值
  return cartList.reduce((sum,item)=>  item.flag ? sum += item.originprice * item.num : sum
  ,0) 
},[cartList])

  // 定义全选状态
  const [checkedAll, setCheckedAll] = useState(false)

  return (
    <div>
      <MyNavBar isShow={false}>购物车<span> ({cartList.length}) </span></MyNavBar>
      {
        isShowEmpty ? <Empty
          style={{ padding: '64px 0' }}
          imageStyle={{ width: 128 }}
          description={
            <div>
              <p style={{
                textAlign: 'center',
                marginBottom: '20px'
              }}>暂无数据</p>
              <Button color='danger' onClick={() => {
                his.push('/home')
              }}>立即购物</Button>
            </div>
          }
        /> : <List>
          {
            cartList.map(item =>
              <SwipeAction
              key={item.proid}
              closeOnAction={true}
              closeOnTouchOutside={true}
              rightActions={[
                {
                  key: 'delete',
                  text: '删除',
                  color: 'danger',
                  onClick:async()=>{
                    await Dialog.confirm({
                      content:'确定要删除吗?',
                      onConfirm(){
                        // !调用删除接口
                        removeApi({
                          cartid:item.cartid
                        }).then(res=>{
                          getCartListFn()
                        })
                      }
                    })
                  }
                },
              ]}
            >
              <List.Item key={item.proid}
              prefix={
                <div style={{
                  display: 'flex',
                  alignItems: 'center'
                }}>
                  <div onClick={e => e.stopPropagation()} style={
                    {
                      marginRight: '5px'
                    }
                  }>
                    <Checkbox checked={item.flag} onChange={(bool)=>{
                      console.log(bool);
                      // !调用接口
                      selectOneApi({
                        cartid:item.cartid,
                        flag:bool
                      }).then(res=>{
                        console.log('select1',res);
                        // !重新调用获取购物车列表接口
                        getCartListFn()
                      })
                    }}/>
                  </div>
                  <Avatar src={item.img1} />
                </div>
              }
              description={
                <div style={{
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center'
                }}>
                  <span style={{
                    color: 'red'
                  }}> ${item.originprice.toFixed(2)} 元</span>
                  <Stepper
                    min={0}
                    value={item.num}
                    onChange={value => {
                      if(value==0){
                        // !!调用删除接口
                        removeApi()
                      }else{
                        updateNumApi({
                          cartid:item.cartid,
                          num:value
                        }).then(res=>{
                          console.log('resupdate',res);
                          // !调用获取购物车数量接口
                          getCartListFn()
                        }) 
                      }
                      // !调用接口 修改数量
                     
                    }}
                  />
                </div>
              }
            > <Ellipsis direction='end' content={item.proname} style={{ fontSize: '15px' }} />
            </List.Item>
            </SwipeAction>
            )
          }
        </List>
      }
      {/* 购物车底部tabbar */}
      <BarStyle>
        <div>
          <Checkbox checked={checkedAll} 
          onChange={(bool)=>{
            console.log('selAll',bool);
            selectAllApi({
              userid:userId,
              type:bool
            }).then(res=>{
              console.log('resall',res);
              getCartListFn()
            })
          }}/>全选
        </div>
        <p>
          合计: { totalPrice.toFixed(2) } 元
        </p>
        <Button color='danger' >合计</Button>
      </BarStyle>

    </div>
  )
}
